#include "event_malloc.h"

event *
event_malloc(event_chunk *chunk) 
{
    int i, found = 0;
    event *ev;

    /*
     * If we have exceeded our chunk bounds, return error.
     */
    if (chunk->inuse >= chunk->size) {
        return NULL;
    }

    /*
     * If there was a recently free'd element, use that first before starting a
     * search.
     */
    if (chunk->last_free >= 0) {
        chunk->last_free = -1;
        chunk->inuse++;
        ev = chunk->data[chunk->last_free];
        memset(ev, 0, sizeof(event));
        return r;
    }

    /*
     * Search the elements to find first free element
     */ 
    for (i = 0; i < chunk->size && !found; i++) {
        ev = chunk->data[i];
        if (ev->code == EVENT_CHUNK_FREE) {
            found = 1;
        }
    }
 
    if (found) {
        chunk->inuse++;
        memset(ev, 0, sizeof(event));
        return ev;
    } else {
        return NULL;
    }
}


void 
event_free(event *ev)
{
    if (ev == NULL) {
        return;
    }

    ev->code = EVENT_CHUNK_FREE;
    ev->chunk->inuse--;
    ev->chunk->last_free = EVENT_CHUNK_INDEX(ev);
}

